from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin

db = SQLAlchemy()


class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    password = db.Column(db.String(80))


# 标签，多对多
post_tags = db.Table(
    "post_tags",
    db.Column(
        "post_id", db.Integer, db.ForeignKey("post.id", name="fk_posttags_post_id")
    ),
    db.Column("tag_id", db.Integer, db.ForeignKey("tag.id", name="fk_posttags_tag_id")),
)


class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(120))
    content = db.Column(db.Text)
    user_id = db.Column(db.Integer, db.ForeignKey("user.id", name="fk_post_user_id"))
    status = db.Column(db.String(10), default='draft')  # 'draft' 或 'published'
    created_at = db.Column(db.Text)
    category_id = db.Column(
        db.Integer, db.ForeignKey("category.id", name="fk_post_category_id")
    )
    tags = db.relationship("Tag", secondary=post_tags, backref="posts")
    user = db.relationship("User", backref="user", uselist=False)


# 分类，一对多
class Category(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False, unique=True)
    posts = db.relationship("Post", backref="category", lazy=True)


class Tag(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30), unique=True)
